package de.tum.in.eist.poll.controller;

import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

import de.tum.in.eist.poll.adapter.LoginAdapter;
import de.tum.in.eist.poll.adapter.ViewCreator;
import de.tum.in.eist.poll.client.EIST_POLL;
import de.tum.in.eist.poll.shared.User;

/**
 * The userController
 * handles login and logout of the user
 * @author sudi
 *
 */
public class UserController {
	private User user = null;
	private ViewCreator view;
	
	public UserController(ViewCreator view) {
		this.view = view;
	}
	
	/**
	 * return if the user is logged in
	 * @return true if user is logged in false otherwise
	 */
	public boolean isLoggedIn() {
		if (user == null)
			rememberMe(null);
		return user == null ? false : true;
	}
	
	/**
	 * logout the user
	 */
	public void logout() {
		user = null;
		Cookies.removeCookie("name");
		Cookies.removeCookie("passwd");
		History.newItem("");
	}
	
	/**
	 * log user in
	 * @param name UserName
	 * @param passwd UserPassword
	 * @param login The LoginAdapter to show feedback
	 */
	public void login(String name, String passwd, final LoginAdapter login) {
		EIST_POLL.getService().login(name, passwd, new AsyncCallback<User>(){

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("User/Password is wrong!");
				if (login != null) {
					login.name.selectAll();
					login.name.setFocus(true);
				}
			}

			@Override
			public void onSuccess(User result) {
				if (login != null) {
					login.loginDialog.removeFromParent();
				}
				view.create_controls(UserController.this);
				user = result;
				Cookies.setCookie("name", user.getName());
				Cookies.setCookie("passwd", user.getPassword());
				History.newItem("user");
			}
		});
	}
	
	/** 
	 * get the current logged in user
	 * 
	 * @return Returns the User or null if not logged in
	 */
	public User getUser() {
		return user;
	}
	
	/**
	 * Checks if the user is already logged in and does it if its the case
	 * Don't call this function
	 * @param l The loginadapter for feedback or null if none is avaible
	 */
	public void rememberMe(LoginAdapter l) {
		String userName = Cookies.getCookie("name");
		String userPasswd = Cookies.getCookie("passwd");
		if (userName == null || userPasswd == null)
			return;
		login(userName, userPasswd, l);
	}
}
